package com.region.http.client.resolver.result;

import com.region.common.adapter.json.JSONAdapter;
import com.region.common.adapter.json.JSONAdapterFactory;
import com.region.common.exception.JsonAdapterException;
import com.region.common.utils.ReflectUtils;
import com.region.http.client.common.Constant;
import com.region.http.client.model.ResponseData;

import java.lang.reflect.Type;
import java.nio.charset.Charset;

/**
 * The Regular Object Resolver
 *
 * @author liujieyu
 * @date 2022/12/2
 */
public class ObjectResultResolver extends AbstractResultResolver {

    @Override
    public boolean isResolver(Type type) {
        Class<?> returnClass = ReflectUtils.transform(type);
        return Object.class.isAssignableFrom(returnClass);
    }

    @Override
    public Object resolver(ResponseData responseData) throws Throwable {
        JSONAdapter adapter = JSONAdapterFactory.getAdapter();
        if (adapter == null) {
            throw new JsonAdapterException("Not found json adapter framework.");
        }
        return adapter.toObject(new String(responseData.getBody(), Charset.defaultCharset()), responseData.getType());
    }

    @Override
    public int getPriority() {
        return Constant.MAX_ORDER;
    }
}
